package com.powernode.queryops;

import com.powernode.commons.util.ReleaseResourceUtils;

import java.sql.*;
import java.util.ResourceBundle;

/**
 * @Author Arrebol
 * @Date 2024/8/1 10:26
 * @Project jdbc
 * @Description：
 * 获取查询结果集
 */
public class JdbcTest1 {
    public static void main(String[] args) {
        //读取属性配置文件
        ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
        String driver = bundle.getString("driver");
        String url = bundle.getString("url");
        String user = bundle.getString("user");
        String password = bundle.getString("password");

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            //注册驱动
            Class.forName(driver);
            //获取连接
            conn = DriverManager.getConnection(url, user, password);
            System.out.println(conn);
            //获取数据库操作对象
            stmt = conn.createStatement();
            //执行SQL语句
            String sql="select id,username,password,real_name from t_user";
            rs = stmt.executeQuery(sql);
            /*
            +----+----------+----------+-----------+
            | id | username | password | real_name |
            +----+----------+----------+-----------+
            |  1 | zhangsan | 123      | 张三      |
            |  2 | admin    | admin123 | 管理员    |
            +----+----------+----------+-----------+
             */
            //处理查询结果集
            //这里的处理方式就是打印输出
            while(rs.next()){
                //取出光标指向的当前行的数据
                //不论数据库中数据是什么形式，统一以字符串形式取出
                //以下的获取方式是通过列下标获取的，列下标从 1 开始
                String id = rs.getString(1);
                String username = rs.getString(2);
                String pwd = rs.getString(3);
                String realName = rs.getString(4);
                System.out.println(id+"\t"+username+"\t"+pwd+"\t"+realName);
            }
            System.out.println("*******************华丽分割线*******************");
            String sql2="select id,name,create_time from t_dept";
            ResultSet rs2 = stmt.executeQuery(sql2);
            System.out.println("-----------------------------");
            while(rs2.next()){
                //以指定的类型获取数据
                int deptId = rs2.getInt(1);
                String deptName = rs2.getString(2);
                Date createTime = rs2.getDate(3);
                System.out.println(deptId+"\t"+deptName+"\t"+createTime);
            }
            System.out.println("-----------------------------");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放资源
            ReleaseResourceUtils.release(rs,stmt,conn);
        }
    }
}
